#include "debug_uart.h"
#include <stdio.h>


void Debug_UART_Init(void) {
    // 使能UART1和GPIOA时钟
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 | RCC_APB2Periph_GPIOA, ENABLE);  // UART1和GPIOA都在APB2总线上

    // GPIO配置
    GPIO_InitTypeDef GPIO_InitStructure;
    
    // 配置TX引脚 PA9
    GPIO_InitStructure.GPIO_Pin = DEBUG_TX_PIN;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(DEBUG_GPIO_PORT, &GPIO_InitStructure);
    
    // 配置RX引脚 PA10
    GPIO_InitStructure.GPIO_Pin = DEBUG_RX_PIN;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
    GPIO_Init(DEBUG_GPIO_PORT, &GPIO_InitStructure);

    // UART配置
    USART_InitTypeDef USART_InitStructure;
    USART_InitStructure.USART_BaudRate = DEBUG_BAUDRATE;
    USART_InitStructure.USART_WordLength = USART_WordLength_8b;
    USART_InitStructure.USART_StopBits = USART_StopBits_1;
    USART_InitStructure.USART_Parity = USART_Parity_No;
    USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
    USART_InitStructure.USART_Mode = USART_Mode_Tx | USART_Mode_Rx;  // 启用收发功能
    USART_Init(DEBUG_UART_PORT, &USART_InitStructure);

    USART_Cmd(DEBUG_UART_PORT, ENABLE);
}

void Debug_Send_Data(ESP32_Data_TypeDef data) {
    char debug_str[96];
    
    // 合并H和L为一个32位值
    uint32_t combined_value = ((uint32_t)data.raw_data[0] << 24) |
                             ((uint32_t)data.raw_data[1] << 16) |
                             ((uint32_t)data.raw_data[2] << 8)  |
                             (uint32_t)data.raw_data[3];
    
    // 显示原始字节和组合后的32位值
    snprintf(debug_str, sizeof(debug_str), 
             "Raw[%02X %02X %02X %02X] -> Value: %lu (0x%08lX)\r\n",
             data.raw_data[0], data.raw_data[1], 
             data.raw_data[2], data.raw_data[3],
             combined_value, combined_value);
    
    char *ptr = debug_str;
    while (*ptr) {
        while (USART_GetFlagStatus(DEBUG_UART_PORT, USART_FLAG_TXE) == RESET);
        USART_SendData(DEBUG_UART_PORT, *ptr++);
    }
}

void Debug_Test(void) {
    char test_str[] = "Debug UART Test\r\n";
    
    while (1) {  // 无限循环
        char *ptr = test_str;
        while (*ptr) {
            while (USART_GetFlagStatus(DEBUG_UART_PORT, USART_FLAG_TXE) == RESET);
            USART_SendData(DEBUG_UART_PORT, *ptr++);
        }
        Delay_Ms(1000);  // 每500ms发送一次，可调整发送间隔
    }
}